import {AfterContentChecked, Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {DataService} from '../data.service';

@Component({
  selector: 'app-good-detail',
  templateUrl: './good-detail.component.html',
  styleUrls: ['./good-detail.component.css']
})
export class GoodDetailComponent implements OnInit, AfterContentChecked {
  foods: any = {};
  isAddCart = false;
  type = 0; // 0-全部 1-满意 2-不满意
  isChecked = true; // 是否选中只看有内容的评论
  ratingsArr = [];
  satRatings = [];
  NotSatRatings = [];
  constructor(private route: ActivatedRoute, private ds: DataService, private router: Router) { }

  ngOnInit() {
    this.route.queryParamMap.subscribe((o: any) => {
      this.foods = JSON.parse(o.params.foods);
    });
    this.satRatings = this.foods.ratings.filter((v) =>  v.rateType === 0 ? true : false);
    this.NotSatRatings = this.foods.ratings.filter((v) =>  v.rateType === 1 ? true : false);
  }

  onAddCart(event) {
    this.ds.sPrice.next({
      price: this.foods.price,
      clientX: event.clientX,
      clientY: event.clientY,
    });
    this.isAddCart = true;
  }

  onDecrease(event) {
    const ele = event.target.nextSibling;
    const num = parseInt(ele.textContent, 10) - 1;
    if ( num === 0 ) {
      this.isAddCart = false;
    }
    if ( num < 0 ) {
      return;
    }
    ele.textContent = num + '';
    this.ds.sPrice.next({
      price: -this.foods.price,
      clientX: event.clientX,
      clientY: event.clientY,
    });
  }

  onIncrease(event) {
    const ele = event.target.previousSibling;
    ele.classList.remove('hidden');
    ele.previousSibling.classList.remove('hidden');
    const num = parseInt(ele.textContent, 10) + 1;
    ele.textContent = num + '';
    this.ds.sPrice.next({
      price: this.foods.price,
      clientX: event.clientX,
      clientY: event.clientY,
    });
  }

  onSatisfy(type, event) {
    this.type = type;
    const cs = event.target.parentNode.children;
    for (let i = 0; i < cs.length; i++) {
      cs[i].classList.remove('active');
    }
    event.target.classList.add('active');
  }

  onChecked() {
    this.isChecked = !this.isChecked;
  }

  ngAfterContentChecked(): void {
    switch (this.type) {
      case 1: this.ratingsArr = this.satRatings; break;
      case 2: this.ratingsArr = this.NotSatRatings; break;
      default: this.ratingsArr = this.foods.ratings; break;
    }
  }

  onClose() {
    this.router.navigate(['/goods'], {
      skipLocationChange: true,
      queryParams: {}
    });
  }
}
